package com.codi.bus.core.service.impl;

import com.codi.base.exception.BaseAppException;
import com.codi.base.util.ListUtil;
import com.codi.base.util.MoneyUtils;
import com.codi.bus.constant.FundConst;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.core.dao.TradeOrderDao;
import com.codi.bus.core.dao.UserDao;
import com.codi.bus.core.domain.User;
import com.codi.bus.core.resultModel.*;
import com.codi.bus.core.service.FundDetailService;
import com.codi.bus.core.service.QueryService;
import com.codi.bus.core.service.StatisticsService;
import com.codi.bus.core.service.model.*;
import com.codi.fundData.dao.FundDetailDao;
import com.codi.fundData.dao.FundInvestAdvisorOutlineDao;
import com.codi.fundData.domain.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by asus on 2018/2/9.
 */

@Service("statisticsService")
@Transactional
public class StatisticsServiceImpl implements StatisticsService {
    private static final Logger logger = LoggerFactory.getLogger(StatisticsServiceImpl.class);

    @Resource(name = "tradeOrderDao")
    private TradeOrderDao tradeOrderDao;

    @Resource(name = "userDao")
    private UserDao userDao;

    @Resource(name = "fundDetailDao")
    private FundDetailDao fundDetailDao;

    @Resource(name = "fundInvestAdvisorOutlineDao")
    private FundInvestAdvisorOutlineDao fundInvestAdvisorOutlineDao;

    @Autowired
    private FundDetailService fundDetailService;

    @Autowired
    private QueryService queryService;

    @Override
    public TradeConfirmResult getTradeConfirmCount(int year, int month, int day){
        Date beginDate = new Date();
        Date endDate = new Date();
        GregorianCalendar gcBegin = new GregorianCalendar();
        gcBegin.set(Calendar.YEAR, year);//设置年
        gcBegin.set(Calendar.MONTH, month);//这里0是1月..以此向后推
        gcBegin.set(Calendar.DAY_OF_MONTH, day);//设置天
        gcBegin.set(Calendar.HOUR_OF_DAY, 0);//设置小时
        gcBegin.set(Calendar.MINUTE, 0);//设置分
        gcBegin.set(Calendar.SECOND, 0);//设置秒
        gcBegin.set(Calendar.MILLISECOND,0);//设置毫秒
        beginDate = gcBegin.getTime();
        GregorianCalendar gcEnd = new GregorianCalendar();
        gcBegin.set(Calendar.YEAR, year);//设置年
        gcBegin.set(Calendar.MONTH, month);//这里0是1月..以此向后推
        gcBegin.set(Calendar.DAY_OF_MONTH, day);//设置天
        gcBegin.set(Calendar.HOUR_OF_DAY, 23);//设置小时
        gcBegin.set(Calendar.MINUTE, 59);//设置分
        gcBegin.set(Calendar.SECOND, 59);//设置秒
        gcBegin.set(Calendar.MILLISECOND,0);//设置毫秒
        endDate = gcEnd.getTime();
        int count = tradeOrderDao.getBuyCountByConfirmDate(beginDate,endDate);
        int amount = tradeOrderDao.getSellByConfirmDate(beginDate, endDate);
        TradeConfirmResult tradeConfirmResult = new TradeConfirmResult();
        tradeConfirmResult.setBuyConfirm(count);
        tradeConfirmResult.setSellConfirm(amount);
        return tradeConfirmResult;
    }


    @Override
    public TradeStatisticsResult getStatistics(int count){
        List<User> users = userDao.getAllUser();
        Map<String, BigDecimal> fundTypeMap = new HashMap<>();
        fundTypeMap.put(GlobalConstant.CURRENCY, BigDecimal.valueOf(0));
        fundTypeMap.put(GlobalConstant.FUND, BigDecimal.valueOf(0));
        fundTypeMap.put(GlobalConstant.BALANCE, BigDecimal.valueOf(0));
        fundTypeMap.put(GlobalConstant.ENTERPRISING, BigDecimal.valueOf(0));
        fundTypeMap.put(GlobalConstant.STEADY, BigDecimal.valueOf(0));

        Map<String, BigDecimal> fundSellMap = new HashMap<>();
        Map<String, BigDecimal> fundCompanyMap = new HashMap<>();
        BuyAssets buyAssets = new BuyAssets();
        buyAssets.setOne(0);
        buyAssets.setTwo(0);
        buyAssets.setThree(0);
        buyAssets.setFour(0);
        buyAssets.setFive(0);
        int c = 0;
        for (User user : users){
            c ++;
            if (c >= count){
                break;
            }
            if (user.getUserId() == null) {
                continue;
            }
            AssetsResult assetsResult = queryService.queryAssets(user.getUserId());
            logger.debug("用户信息：{}",user.getUserName());
            if (assetsResult == null || assetsResult.getFund() == null || assetsResult.getWallet() == null || assetsResult.getPortfolios() == null) {
                continue;
            }
            //普通基金
            for (AssetFundModel assetFundModel : assetsResult.getFund().getFundModelList()){
                //通过基金类型区分
                logger.debug("基金类型：{}",assetFundModel.getIsCurrency());
                if (assetFundModel.getIsCurrency()){
                    fundTypeMap.put(GlobalConstant.CURRENCY, MoneyUtils.add(fundTypeMap.get(GlobalConstant.CURRENCY), assetFundModel.getTotalWorthValue()));
                }else {
                    fundTypeMap.put(GlobalConstant.FUND, MoneyUtils.add(fundTypeMap.get(GlobalConstant.FUND), assetFundModel.getTotalWorthValue()));
                }
                logger.debug("基金编码：{}",assetFundModel.getFundCode());
                //通过基金编码区分
                if (!fundSellMap.containsKey(assetFundModel.getFundCode())){
                    fundSellMap.put(assetFundModel.getFundCode(), assetFundModel.getTotalWorthValue());
                } else {
                    fundSellMap.put(assetFundModel.getFundCode(), MoneyUtils.add(fundSellMap.get(assetFundModel.getFundCode()),assetFundModel.getTotalWorthValue()));
                }
                //通过基金公司区分

//                SecurityProduct product = fundDetailService.getProduct(assetFundModel.getFundCode());
//                FundDetail fundDetail = fundDetailDao.queryFundDetail(product.getInnerCode());
//                FundInvestAdvisorOutline investAdvisor = fundInvestAdvisorOutlineDao.selectFundInvestAdvisor(fundDetail
//                    .getInvestAdvisorCode());
                FundDetailResult fundDetailResult = new FundDetailResult();
                try {
                    fundDetailResult = fundDetailService.getFundDetailByFundCode(assetFundModel.getFundCode(), user.getUserId());
                } catch (BaseAppException e) {
                    e.printStackTrace();
                }

                logger.debug("基金公司：{}",fundDetailResult.getInvestAdvisor());
                if (!fundCompanyMap.containsKey(fundDetailResult.getInvestAdvisor())){
                    fundCompanyMap.put(fundDetailResult.getInvestAdvisor(), assetFundModel.getTotalWorthValue());
                } else {
                    fundCompanyMap.put(fundDetailResult.getInvestAdvisor(), MoneyUtils.add(fundCompanyMap.get(fundDetailResult.getInvestAdvisor()),assetFundModel.getTotalWorthValue()));
                }
            }
            //  瑞富宝
            for (AssetFundModel assetFundModel : assetsResult.getWallet().getFundModelList()){
                fundTypeMap.put(GlobalConstant.CURRENCY, MoneyUtils.add(fundTypeMap.get(GlobalConstant.CURRENCY), assetFundModel.getTotalWorthValue()));
                if (!fundSellMap.containsKey(assetFundModel.getFundCode())){
                    fundSellMap.put(assetFundModel.getFundCode(), assetFundModel.getTotalWorthValue());
                } else {
                    fundSellMap.put(assetFundModel.getFundCode(), MoneyUtils.add(fundSellMap.get(assetFundModel.getFundCode()),assetFundModel.getTotalWorthValue()));
                }
                //通过基金公司区分
//                SecurityProduct product = fundDetailService.getProduct(assetFundModel.getFundCode());
//                FundDetail fundDetail = fundDetailDao.queryFundDetail(product.getInnerCode());
//                FundInvestAdvisorOutline investAdvisor = fundInvestAdvisorOutlineDao.selectFundInvestAdvisor(fundDetail
//                    .getInvestAdvisorCode());
//                logger.debug("基金公司：{}",investAdvisor.getInvestAdvisorName());
//                if (!fundCompanyMap.containsKey(investAdvisor.getInvestAdvisorName())){
//                    fundCompanyMap.put(investAdvisor.getInvestAdvisorName(), assetFundModel.getTotalWorthValue());
//                } else {
//                    fundCompanyMap.put(investAdvisor.getInvestAdvisorName(), MoneyUtils.add(fundCompanyMap.get(assetFundModel.getFundCode()),assetFundModel.getTotalWorthValue()));
//                }
                FundDetailResult fundDetailResult = new FundDetailResult();
                try {
                    fundDetailResult = fundDetailService.getFundDetailByFundCode(assetFundModel.getFundCode(), user.getUserId());
                } catch (BaseAppException e) {
                    e.printStackTrace();
                }

                logger.debug("基金公司：{}",fundDetailResult.getInvestAdvisor());
                if (!fundCompanyMap.containsKey(fundDetailResult.getInvestAdvisor())){
                    fundCompanyMap.put(fundDetailResult.getInvestAdvisor(), assetFundModel.getTotalWorthValue());
                } else {
                    fundCompanyMap.put(fundDetailResult.getInvestAdvisor(), MoneyUtils.add(fundCompanyMap.get(fundDetailResult.getInvestAdvisor()),assetFundModel.getTotalWorthValue()));
                }
            }
            // 组合
            for (PortfolioModel portfolioModel : assetsResult.getPortfolios().getPortfolios()){
                logger.debug("组合编码：{}",portfolioModel.getPortfolioCode());
                switch (portfolioModel.getPortfolioCode()) {
                    case GlobalConstant.ENTERPRISINGCODE :
                        fundTypeMap.put(GlobalConstant.ENTERPRISING, MoneyUtils.add(fundTypeMap.get(GlobalConstant.ENTERPRISING), portfolioModel.getPortfolioWorthValue()));
                        break;
                    case GlobalConstant.BALANCECODE :
                        fundTypeMap.put(GlobalConstant.BALANCE, MoneyUtils.add(fundTypeMap.get(GlobalConstant.BALANCE), portfolioModel.getPortfolioWorthValue()));
                        break;
                    case GlobalConstant.STEADYCODE :
                        fundTypeMap.put(GlobalConstant.STEADY, MoneyUtils.add(fundTypeMap.get(GlobalConstant.STEADY), portfolioModel.getPortfolioWorthValue()));
                        break;
                }
                for (AssetFundModel assetFundModel : portfolioModel.getPortfolioFunds()){
                    logger.debug("组合中编码：{}",assetFundModel.getFundCode());
                    //通过基金编码区分
                    if (!fundSellMap.containsKey(assetFundModel.getFundCode())){
                        fundSellMap.put(assetFundModel.getFundCode(), assetFundModel.getTotalWorthValue());
                    } else {
                        fundSellMap.put(assetFundModel.getFundCode(), MoneyUtils.add(fundSellMap.get(assetFundModel.getFundCode()),assetFundModel.getTotalWorthValue()));
                    }
                    //通过基金公司区分
//                    SecurityProduct product = fundDetailService.getProduct(assetFundModel.getFundCode());
//                    FundDetail fundDetail = fundDetailDao.queryFundDetail(product.getInnerCode());
//                    FundInvestAdvisorOutline investAdvisor = fundInvestAdvisorOutlineDao.selectFundInvestAdvisor(fundDetail
//                        .getInvestAdvisorCode());
//                    logger.debug("基金公司：{}",investAdvisor.getInvestAdvisorName());
//                    if (!fundCompanyMap.containsKey(investAdvisor.getInvestAdvisorName())){
//                        fundCompanyMap.put(investAdvisor.getInvestAdvisorName(), assetFundModel.getTotalWorthValue());
//                    } else {
//                        fundCompanyMap.put(investAdvisor.getInvestAdvisorName(), MoneyUtils.add(fundCompanyMap.get(assetFundModel.getFundCode()),assetFundModel.getTotalWorthValue()));
//                    }
                    FundDetailResult fundDetailResult = new FundDetailResult();
                    try {
                        fundDetailResult = fundDetailService.getFundDetail(assetFundModel.getFundCode(), user.getUserId());
                    } catch (BaseAppException e) {
                        e.printStackTrace();
                    }





                    logger.debug("基金公司：{}",fundDetailResult.getInvestAdvisor());
                    if (!fundCompanyMap.containsKey(fundDetailResult.getInvestAdvisor())){
                        fundCompanyMap.put(fundDetailResult.getInvestAdvisor(), assetFundModel.getTotalWorthValue());
                    } else {
                        fundCompanyMap.put(fundDetailResult.getInvestAdvisor(), MoneyUtils.add(fundCompanyMap.get(fundDetailResult.getInvestAdvisor()),assetFundModel.getTotalWorthValue()));
                    }
                }
            }
            //普通基金交易记录
            ApplyListResult result = queryService.queryApplys(user.getUserId(), GlobalConstant.MAX_REQUEST_NUM, 1, 1, "1", true);
            //瑞富宝交易记录
            ApplyListResult result1 = queryService.queryWalletOperationList(user.getUserId(), GlobalConstant.MAX_REQUEST_NUM, 1, 1, "0","");
            //组合交易记录
            PortfolioApplyListResult result2 = queryService.queryPortfolioApplys(user.getUserId(), GlobalConstant.MAX_REQUEST_NUM, 1, 1, "1", true);
            //按购买金额区分
            //普通基金
            for (ApplyModel applyModel : result.getApplys()){
                if (GlobalConstant.TACONFIRM_FLAG_CONFIRMED.equals(applyModel.getTAConfirmFlag()) && GlobalConstant.FUND_BUSIN_CODE_APPLY_BUY.equals(applyModel.getFundBusinCode())){
                    if (MoneyUtils.compareTo(applyModel.getBalance(),1000) == -1 && MoneyUtils.compareTo(applyModel.getBalance(),0) == 1 || MoneyUtils.compareTo(applyModel.getBalance(),1000) == 0){
                        logger.debug("原0-1000笔数：{}",buyAssets.getOne());
                        logger.debug("balance：{}",applyModel.getBalance());
                        buyAssets.setOne(buyAssets.getOne() + 1);
                        logger.debug("新0-1000笔数：{}",buyAssets.getOne());
                    }
                    if (MoneyUtils.compareTo(applyModel.getBalance(),5000) == -1 && MoneyUtils.compareTo(applyModel.getBalance(),1000) == 1 || MoneyUtils.compareTo(applyModel.getBalance(),5000) == 0){
                        buyAssets.setTwo(buyAssets.getTwo() + 1);
                    }
                    if (MoneyUtils.compareTo(applyModel.getBalance(),10000) == -1 && MoneyUtils.compareTo(applyModel.getBalance(),5000) == 1 || MoneyUtils.compareTo(applyModel.getBalance(),10000) == 0){
                        buyAssets.setThree(buyAssets.getThree() + 1);
                    }
                    if (MoneyUtils.compareTo(applyModel.getBalance(),50000) == -1 && MoneyUtils.compareTo(applyModel.getBalance(),10000) == 1 || MoneyUtils.compareTo(applyModel.getBalance(),50000) == 0){
                        buyAssets.setFour(buyAssets.getFour() + 1);
                    }
                    if ( MoneyUtils.compareTo(applyModel.getBalance(),50000) == 1 ){
                        buyAssets.setFive(buyAssets.getFive() + 1);
                    }
                }
            }
            //瑞富宝
            for (ApplyModel applyModel : result1.getApplys()){
                if (GlobalConstant.TACONFIRM_FLAG_CONFIRMED.equals(applyModel.getTAConfirmFlag()) && GlobalConstant.FUND_BUSIN_CODE_APPLY_BUY.equals(applyModel.getFundBusinCode())){
                    if (MoneyUtils.compareTo(applyModel.getBalance(),1000) == -1 && MoneyUtils.compareTo(applyModel.getBalance(),0) == 1 || MoneyUtils.compareTo(applyModel.getBalance(),1000) == 0){
                        logger.debug("原0-1000笔数：{}",buyAssets.getOne());
                        logger.debug("balance：{}",applyModel.getBalance());
                        buyAssets.setOne(buyAssets.getOne() + 1);
                        logger.debug("新0-1000笔数：{}",buyAssets.getOne());
                    }
                    if (MoneyUtils.compareTo(applyModel.getBalance(),10000) == -1 && MoneyUtils.compareTo(applyModel.getBalance(),5000) == 1 || MoneyUtils.compareTo(applyModel.getBalance(),10000) == 0){
                        buyAssets.setThree(buyAssets.getThree() + 1);
                    }
                    if (MoneyUtils.compareTo(applyModel.getBalance(),5000) == -1 && MoneyUtils.compareTo(applyModel.getBalance(),1000) == 1 || MoneyUtils.compareTo(applyModel.getBalance(),5000) == 0){
                        buyAssets.setTwo(buyAssets.getTwo() + 1);
                    }
                    if (MoneyUtils.compareTo(applyModel.getBalance(),50000) == -1 && MoneyUtils.compareTo(applyModel.getBalance(),10000) == 1 || MoneyUtils.compareTo(applyModel.getBalance(),50000) == 0){
                        buyAssets.setFour(buyAssets.getFour() + 1);
                    }
                    if ( MoneyUtils.compareTo(applyModel.getBalance(),50000) == 1 ){
                        buyAssets.setFive(buyAssets.getFive() + 1);
                    }
                }
            }
            //组合
            for (ApplyModel applyModel : result2.getApplys()){
                if (GlobalConstant.TACONFIRM_FLAG_CONFIRMED.equals(applyModel.getTAConfirmFlag()) && GlobalConstant.FUND_BUSIN_CODE_APPLY_BUY.equals(applyModel.getFundBusinCode())){
                    if (MoneyUtils.compareTo(applyModel.getBalance(),1000) == -1 && MoneyUtils.compareTo(applyModel.getBalance(),0) == 1 || MoneyUtils.compareTo(applyModel.getBalance(),1000) == 0){
                        logger.debug("原0-1000笔数：{}",buyAssets.getOne());
                        logger.debug("balance：{}",applyModel.getBalance());
                        buyAssets.setOne(buyAssets.getOne() + 1);
                        logger.debug("新0-1000笔数：{}",buyAssets.getOne());
                    }
                    if (MoneyUtils.compareTo(applyModel.getBalance(),10000) == -1 && MoneyUtils.compareTo(applyModel.getBalance(),5000) == 1 || MoneyUtils.compareTo(applyModel.getBalance(),10000) == 0){
                        buyAssets.setThree(buyAssets.getThree() + 1);
                    }
                    if (MoneyUtils.compareTo(applyModel.getBalance(),5000) == -1 && MoneyUtils.compareTo(applyModel.getBalance(),1000) == 1 || MoneyUtils.compareTo(applyModel.getBalance(),5000) == 0){
                        buyAssets.setTwo(buyAssets.getTwo() + 1);
                    }
                    if ( MoneyUtils.compareTo(applyModel.getBalance(),50000) == 1 ){
                        buyAssets.setFive(buyAssets.getFive() + 1);
                    }
                    if (MoneyUtils.compareTo(applyModel.getBalance(),50000) == -1 && MoneyUtils.compareTo(applyModel.getBalance(),10000) == 1 || MoneyUtils.compareTo(applyModel.getBalance(),50000) == 0){
                        buyAssets.setFour(buyAssets.getFour() + 1);
                    }
                }
            }
        }
        List<FundSellModel> fundSellModels = new ArrayList<>();
        for (String fundCode : fundSellMap.keySet()){
            logger.debug("基金循环：{}",fundCode);
            FundSellModel fundSellModel = new FundSellModel();
            fundSellModel.setFundCode(fundCode);
            fundSellModel.setAssets(fundSellMap.get(fundCode));
            fundSellModels.add(fundSellModel);
        }

        Collections.sort(fundSellModels, new Comparator<FundSellModel>() {
            @Override
            public int compare(FundSellModel o1, FundSellModel o2) {
                logger.debug("基金排序");
                BigDecimal o1No = o1.getAssets(), o2No = o2.getAssets();
                return 0 - o1No.compareTo(o2No);
            }
        });
        List<FundCompanyModel> fundCompanyModels = new ArrayList<>();
        for (String company : fundCompanyMap.keySet()){
            logger.debug("基金公司循环：{}",company);
            FundCompanyModel fundCompanyModel = new FundCompanyModel();
            fundCompanyModel.setCompany(company);
            fundCompanyModel.setAssets(fundCompanyMap.get(company));
            fundCompanyModels.add(fundCompanyModel);
        }
        Collections.sort(fundCompanyModels, new Comparator<FundCompanyModel>() {
            @Override
            public int compare(FundCompanyModel o1, FundCompanyModel o2) {
                logger.debug("基金公司排序");
                BigDecimal o1No = o1.getAssets(), o2No = o2.getAssets();
                return 0 - o1No.compareTo(o2No);
            }
        });

        TradeStatisticsResult tradeStatisticsResult = new TradeStatisticsResult();
        tradeStatisticsResult.setBuyAssets(buyAssets);
        tradeStatisticsResult.setFundCompanyModels(fundCompanyModels);
        tradeStatisticsResult.setFundSellModels(fundSellModels);
        tradeStatisticsResult.setFundTypeMap(fundTypeMap);
        logger.debug("结束");
        return tradeStatisticsResult;

    }

}
